#!/usr/local/bin/perl

use strict;
use LWP::UserAgent;
use Crypt::SSLeay;
use JSON;
use HTTP::Cookies;
use HTTP::Status;
use Data::Dumper;

if ($#ARGV+1 != 2){
   die "You need to pass in http://host csvfilePath I.E.: perl ChemicalMigration.pl http://retina:9090 /local/dudley/Chemical.csv"
}
my ($host, $csvFile) = @ARGV;

my $browser = LWP::UserAgent->new;
$browser->protocols_allowed( [ 'http', 'https'] );
my $cookieFile = "addama_lwp_cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
    file => $cookieFile,
  );
$cookie_jar->load($cookieFile);
$browser->cookie_jar($cookie_jar);
$browser->timeout(100);
$browser->env_proxy;
open (MYFILE, $csvFile);
my $i = 1;
my $chopped = '';
my $chemicalKey = '';
my $chemicalName = '';
my $reorderKey = '';
my $yoPostCreate = '';
my $anno;
my $json = new JSON;
my $obj;
my $count = 0;
my $maxStrainNumber = 0;
while (<MYFILE>) {
  chomp;
  print "line $count $_\n";
  $yoPostCreate = "\"" . $host . "/addama-rest/dudley-sample/path/datasource/Chemical/";
  $count = $count + 1;
  processLine($_);
  #$count = $count + 1;
}
close (MYFILE);
annotateYO();

sub annotateYO{
   my $postYOAnnotations = $host . '/addama-rest/dudley-sample/path/datasource/Chemical/' .'/annotations?JSON={chemicalCount:' .$count . ';chemicalMaxNum:' . $count .'}';
   my $countAnnoResponse = $browser->post($postYOAnnotations);
   if ($countAnnoResponse->is_success) {
      print("Posted chemical record count Annotations: -> $count");
   }
}

sub processLine{
  my $line = $_[0];
  my @splValues = split('","', $line);
  $i = 1;
  foreach my $val (@splValues) {
  #chop " off first value's beginning, offset of 1 to length
  if ($i == 1){
     $chemicalName = substr($val, 1, (length($val)-1));
     #split strain name and capture max strain number
     #my @oligoNameArray = split($oligoType, $oligoName);
     #my $oligoNumber = $oligoNameArray[1];
     #print("oligo number $oligoNumber\n");
     $chemicalKey = 'CHEM' . $count;
     $yoPostCreate = $yoPostCreate . $chemicalKey .'/create?JSON={chemicalKey:CHEM' . $count . ';chemicalName:\'' . $chemicalName . '\'';
  }elsif ($i == 2) {
     $anno = ';location:\'' . $val . '\'';
     $yoPostCreate = $yoPostCreate . $anno;
  }elsif ($i == 3) {
     $reorderKey = substr($val,0,(length($val)-2));
     $anno = ';reorderKey:\''. $reorderKey . '\'';
     $yoPostCreate = $yoPostCreate . $anno . '}"';
     #$yoPostCreate = $yoPostCreate .'}"';
     print("\nPOST this request\n: $yoPostCreate\n");
     my $response = $browser->post($yoPostCreate);
     if ($response->is_success) {
          my $response = $response->content;
          # eval in case response isn't legit json
          eval { $obj = $json->decode($response) };
          print("$yoPostCreate POSTED Successfully\n");
      }
      else {
          if($response->code()==401) {
            print "\nLogin is required, please run AddamaLogin.pl and try again.\n\n"
          } else {
            print ("POST FAILED");
            die $response->status_line;
          }
      }

   $yoPostCreate = '';
  }
   $i++;
 }
}

